#include "ShortDelay.h"
#include <time.h>
#include <math.h>

//#define TEST

#ifdef TEST
#include <stdio.h>
#endif


static double DelayCountFactor = 0.0;
static long DelayCountOffset = 0;


void ShortDelay(double ys)
	{
	int x = 13;
	for (long i = long(ys * DelayCountFactor) - DelayCountOffset ; i > 0 ; i--) 
		x = abs(x);
	}


void ShortDelayInit(double PresetFactor, long PresetOffset)
	{
	double NewTime, NominalTime, Factor;
	clock_t Start, End;
	
	if (PresetFactor > 0.0)
		{
		DelayCountFactor = PresetFactor;
		DelayCountOffset = PresetOffset;
		return;
		}

	if (PresetFactor == 0.0 && DelayCountFactor > 0.0)
		return;

	DelayCountFactor = 1.0;

	NominalTime = 800.0; //ms

	do 
		{
		Start = clock();
		ShortDelay(NominalTime * 1000.0);
		End = clock();

		NewTime = (double) (End - Start) / (double) CLOCKS_PER_SEC * 1000.0;
		if (NewTime > 0.0)
			Factor = NominalTime / NewTime;
		else
			Factor = 10.0;

		if (Factor > 10.0)
			Factor = 10.0;
		else if (Factor < 0.2)
			Factor = 0.2;

		DelayCountFactor = DelayCountFactor * Factor;

#ifdef TEST
		printf("NewTime = %.4f, Factor = %.5f, DelayCountF = %.2f\n", 
			   NewTime, Factor, DelayCountFactor);
#endif
		} while (Factor <= 0.95 || Factor >= 1.05);


#ifdef NOCH_NICHT_GANZ_FERTIG

	while (true)
		{
		Start = clock();
		for (long i = long(NominalTime / 0.01 /* 0.01 ms */) ; i > 0 ; i--)
			ShortDelay(10.0); /* = 10 ys */
		End = clock();

		NewTime = (double) (End - Start) / (double) CLOCKS_PER_SEC * 1000.0;

		DelayCountOffset = DelayCountFactor * Factor;

		printf("NewTime = %.4f, Factor = %.5f, DelayCountF = %.2f\n", NewTime, Factor, DelayCountFactor);
		} while (Factor <= 0.95 || Factor >= 1.05);

#endif

	}
